package security.utils;

import framework.config.SecurityConfig;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Random;

/**
 * 安全组件TOKEN工具
 */
public class SecurityTokenUtil {
    /**
     * 获取令牌
     *
     * @param request
     * @param securityConfig
     * @return
     */
    public static TokenDetail getRequestToken(HttpServletRequest request, SecurityConfig securityConfig) {
        String requestToken = request.getHeader("Authorization");
        boolean hasToken = StringUtils.hasLength(requestToken);
        if (hasToken && Objects.equals(true, securityConfig.getEnableBearerToken()) && requestToken.startsWith("Bearer ")) {
            return new TokenDetail(requestToken.substring(7), requestToken, TokenChannel.Bearer);
        }
        if (hasToken && Objects.equals(true, securityConfig.getEnableBasicAuth()) && requestToken.startsWith("Basic ")) {
            return new TokenDetail(requestToken.substring(6), requestToken, TokenChannel.Basic);
        }
//        if (hasToken && Objects.equals(true, securityConfig.getEnableBasicOauth()) && requestToken.startsWith("OAuth ")) {
//            return new TokenDetail(requestToken.substring(6), TokenChannel.OAuth);
//        }
        String tokenParamName = securityConfig.getTokenParamName();
        if (StringUtils.hasText(tokenParamName)) {
            String token = request.getParameter(tokenParamName);
            if (StringUtils.hasText(token)) {
                return new TokenDetail(token, TokenChannel.Bearer.name() + " " + token, TokenChannel.Query);
            }
            if (request.getCookies() != null) {
                for (Cookie cookie : request.getCookies()) {
                    if (tokenParamName.equals(cookie.getName())) {
                        if (cookie.getValue() != null && StringUtils.hasText(cookie.getValue())) {
                            return new TokenDetail(cookie.getValue().trim()
                                    , TokenChannel.Bearer.name() + " " + cookie.getValue().trim()
                                    , TokenChannel.Cookie);
                        }
                        break;
                    }
                }
            }
        }
        return null;
    }

}
